package com.ruoyi.common.utils;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.base.Splitter;
import okhttp3.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.DefaultProxyRoutePlanner;
import org.apache.http.protocol.HTTP;
import org.apache.http.ssl.SSLContexts;
import org.apache.http.util.EntityUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.net.ssl.*;
import java.io.*;
import java.net.*;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * 通用http发送方法
 *
 * @author ldwallen
 */
public class HttpUtils {
    private static final Logger log = LoggerFactory.getLogger(HttpUtils.class);
    public static final String IP_URL = "tps133.kdlapi.com:15818";
    private static int readTimeOut = 300000;
    private static int connectTimeOut = 300000;
    private static HttpTransport httpTransport = new HttpTransport();
    private static HttpPost method = null;
    static
    {
        method = new HttpPost();
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(readTimeOut).setConnectTimeout(connectTimeOut)
                .setConnectionRequestTimeout(connectTimeOut).build();
        method.setHeader(HTTP.CONTENT_ENCODING, "UTF-8");
        method.setHeader(HTTP.USER_AGENT, "Rich Powered/1.0");
        method.setHeader(HTTP.CONTENT_TYPE, "application/x-www-form-urlencoded");
        method.setConfig(requestConfig);
    }
    /**
     * 向指定 URL 发送GET方法的请求
     *
     * @param url   发送请求的 URL
     * @param param 请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
     * @return 所代表远程资源的响应结果
     */
    public static String sendGet(String url, String param, String cookie) {
        StringBuilder result = new StringBuilder();
        BufferedReader in = null;
        try {
            String urlNameString = url;
            if (StringUtils.isNotBlank(param)) {
                urlNameString += "?" + param;
            }

            log.info("sendGet - {}", urlNameString);
            URL realUrl = new URL(urlNameString);
            URLConnection connection = realUrl.openConnection();
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent", "Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.111 Mobile Safari/537.36");
            if (StringUtils.isNotBlank(cookie)) {
                connection.setRequestProperty("cookie", cookie);
            }
            connection.connect();
            in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result.append(line);
            }
            log.info("recv - {}", result);
        } catch (ConnectException e) {
            log.error("调用HttpUtils.sendGet ConnectException, url=" + url + ",param=" + param, e);
        } catch (SocketTimeoutException e) {
            log.error("调用HttpUtils.sendGet SocketTimeoutException, url=" + url + ",param=" + param, e);
        } catch (IOException e) {
            log.error("调用HttpUtils.sendGet IOException, url=" + url + ",param=" + param, e);
        } catch (Exception e) {
            log.error("调用HttpsUtil.sendGet Exception, url=" + url + ",param=" + param, e);
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception ex) {
                log.error("调用in.close Exception, url=" + url + ",param=" + param, ex);
            }
        }
        return result.toString();
    }

    /**
     * 向指定 URL 发送POST方法的请求
     *
     * @param url   发送请求的 URL
     * @param param 请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
     * @return 所代表远程资源的响应结果
     */
    public static String sendPost(String url, String param, String cookie) {
        PrintWriter out = null;
        BufferedReader in = null;
        StringBuilder result = new StringBuilder();
        try {
            String urlNameString = url + "?" + param;
            log.info("sendPost - {}", urlNameString);
            URL realUrl = new URL(urlNameString);
            URLConnection conn = realUrl.openConnection();
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent", "Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.111 Mobile Safari/537.36");
            conn.setRequestProperty("Accept-Charset", "utf-8");
            conn.setRequestProperty("contentType", "application/x-www-form-urlencoded");
            if (StringUtils.isNotBlank(cookie)) {
                conn.setRequestProperty("cookie", cookie);
            }
            conn.setDoOutput(true);
            conn.setDoInput(true);
            out = new PrintWriter(conn.getOutputStream());
            out.print(param);
            out.flush();
            in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
            String line;
            while ((line = in.readLine()) != null) {
                result.append(line);
            }
            //log.info("recv - {}", result);
        } catch (ConnectException e) {
            log.error("调用HttpUtils.sendPost ConnectException, url=" + url + ",param=" + param, e);
        } catch (SocketTimeoutException e) {
            log.error("调用HttpUtils.sendPost SocketTimeoutException, url=" + url + ",param=" + param, e);
        } catch (IOException e) {
            log.error("调用HttpUtils.sendPost IOException, url=" + url + ",param=" + param, e);
        } catch (Exception e) {
            log.error("调用HttpsUtil.sendPost Exception, url=" + url + ",param=" + param, e);
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                log.error("调用in.close Exception, url=" + url + ",param=" + param, ex);
            }
        }
        return result.toString();
    }

    public static String sendSSLPost(String url) {
        StringBuilder result = new StringBuilder();
        String urlNameString = url ;
        try {
            log.info("sendSSLPost - {}", urlNameString);
            SSLContext sc = SSLContext.getInstance("SSL");
            sc.init(null, new TrustManager[]{new TrustAnyTrustManager()}, new java.security.SecureRandom());
            URL console = new URL(urlNameString);
            HttpsURLConnection conn = (HttpsURLConnection) console.openConnection();
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            conn.setRequestProperty("Accept-Charset", "utf-8");
            conn.setRequestProperty("contentType", "utf-8");
            conn.setDoOutput(true);
            conn.setDoInput(true);

            conn.setSSLSocketFactory(sc.getSocketFactory());
            conn.setHostnameVerifier(new TrustAnyHostnameVerifier());
            conn.connect();
            InputStream is = conn.getInputStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(is));
            String ret = "";
            while ((ret = br.readLine()) != null) {
                if (ret != null && !ret.trim().equals("")) {
                    result.append(new String(ret.getBytes("ISO-8859-1"), "utf-8"));
                }
            }
            log.info("recv - {}", result);
            conn.disconnect();
            br.close();
        } catch (ConnectException e) {
            log.error("调用HttpUtils.sendSSLPost ConnectException, url=" + url , e);
        } catch (SocketTimeoutException e) {
            log.error("调用HttpUtils.sendSSLPost SocketTimeoutException, url=" + url , e);
        } catch (IOException e) {
            log.error("调用HttpUtils.sendSSLPost IOException, url=" + url , e);
        } catch (Exception e) {
            log.error("调用HttpsUtil.sendSSLPost Exception, url=" + url , e);
        }
        return result.toString();
    }

    private static class TrustAnyTrustManager implements X509TrustManager {
        @Override
        public void checkClientTrusted(X509Certificate[] chain, String authType) {
        }

        @Override
        public void checkServerTrusted(X509Certificate[] chain, String authType) {
        }

        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return new X509Certificate[]{};
        }
    }

    private static class TrustAnyHostnameVerifier implements HostnameVerifier {
        @Override
        public boolean verify(String hostname, SSLSession session) {
            return true;
        }
    }
    public static String sendGetRequest(String url, String param, Map<String, String> headMap) {
        String responseContent = "";
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse response = null;
        try {
            HttpPost httpPost = new HttpPost(url);
            StringEntity entity = new StringEntity(param, "utf-8");// 解决中文乱码问题
            httpPost.setEntity(entity);
            httpPost.addHeader(HTTP.CONTENT_TYPE, "application/x-www-form-urlencoded");
            Iterator var12 = headMap.entrySet().iterator();

            while (var12.hasNext()) {
                Map.Entry<String, String> header = (Map.Entry) var12.next();
                httpPost.addHeader((String) header.getKey(), (String) header.getValue());
            }

            httpClient = HttpClients.createDefault();
            response = httpClient.execute(httpPost);
//            System.out.println(response.getStatusLine().getStatusCode() + "\n");
            HttpEntity result = response.getEntity();
            responseContent = EntityUtils.toString(result, "UTF-8");
//            System.out.println(responseContent);
        } catch (Exception e) {
            System.out.println("发送 POST 请求出现异常！" + e);
            e.printStackTrace();
        }
        // 使用finally块来关闭输出流、输入流
        finally {
            try {
                if (httpClient != null) {
                    httpClient.close();
                }
                if (response != null) {
                    response.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        return responseContent;
    }

    public static String sendPostRequest(String url, String param, Map<String, String> headMap) {
        String responseContent = "";
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse response = null;
        try {
            HttpPost httpPost = new HttpPost(url);
            StringEntity entity = new StringEntity(param, "utf-8");// 解决中文乱码问题
            httpPost.setEntity(entity);
            httpPost.addHeader(HTTP.CONTENT_TYPE, "application/x-www-form-urlencoded");
            Iterator var12 = headMap.entrySet().iterator();

            while (var12.hasNext()) {
                Map.Entry<String, String> header = (Map.Entry) var12.next();
                httpPost.addHeader((String) header.getKey(), (String) header.getValue());
            }

            httpClient = HttpClients.createDefault();
            response = httpClient.execute(httpPost);
//            System.out.println(response.getStatusLine().getStatusCode() + "\n");
            HttpEntity result = response.getEntity();
            responseContent = EntityUtils.toString(result, "UTF-8");
//            System.out.println(responseContent);
        } catch (Exception e) {
            System.out.println("发送 POST 请求出现异常！" + e);
            e.printStackTrace();
        }
        // 使用finally块来关闭输出流、输入流
        finally {
            try {
                if (httpClient != null) {
                    httpClient.close();
                }
                if (response != null) {
                    response.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        return responseContent;
    }

    public static String sendPostRequestByProxyIp(String url, String param, Map<String, String> headMap, String proxyIp) {
        String responseContent = "";
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse response = null;
        String[] proxyInfo = proxyIp.split(":");

        HttpHost proxy = new HttpHost(proxyInfo[0], Integer.parseInt(proxyInfo[1]));
        DefaultProxyRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxy);

        try {
            HttpPost httpPost = new HttpPost(url);
            StringEntity entity = new StringEntity(param, "utf-8");// 解决中文乱码问题
            httpPost.setEntity(entity);
            httpPost.addHeader(HTTP.CONTENT_TYPE, "application/x-www-form-urlencoded");
            Iterator var12 = headMap.entrySet().iterator();

            while (var12.hasNext()) {
                Map.Entry<String, String> header = (Map.Entry) var12.next();
                httpPost.addHeader((String) header.getKey(), (String) header.getValue());
            }

            httpClient = HttpClients.custom()
                    .setRoutePlanner(routePlanner)
                    .build();
            response = httpClient.execute(httpPost);
//            System.out.println(response.getStatusLine().getStatusCode() + "\n");
            HttpEntity result = response.getEntity();
            responseContent = EntityUtils.toString(result, "UTF-8");
//            System.out.println(responseContent);
        } catch (Exception e) {
            System.out.println("发送 POST 请求出现异常！" + e);
            e.printStackTrace();
        }
        // 使用finally块来关闭输出流、输入流
        finally {
            try {
                if (httpClient != null) {
                    httpClient.close();
                }
                if (response != null) {
                    response.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        return responseContent;
    }

    public static String sendJsonMessageByProxyIp(String reqUrl, HashMap<String, String> requestHeaderMap, String jsonStr, String proxyIp) {
        CloseableHttpResponse response = null;
        CloseableHttpClient client = null;
        String resultStr = null;
        try {
            String[] proxyInfo = proxyIp.split(":");
            HttpHost proxy = new HttpHost(proxyInfo[0], Integer.parseInt(proxyInfo[1]));
            DefaultProxyRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxy);
            HttpPost httpPost = new HttpPost(reqUrl);
            StringEntity entityParams = new StringEntity(jsonStr, "utf-8");
            httpPost.setEntity(entityParams);
            httpPost.setHeader("Content-Type", "application/json");
            Iterator var12 = requestHeaderMap.entrySet().iterator();
            while (var12.hasNext()) {
                Map.Entry<String, String> header = (Map.Entry) var12.next();
                httpPost.setHeader((String) header.getKey(), (String) header.getValue());
            }
//            client = HttpClients.createDefault();
            client = HttpClients.custom()
                    .setRoutePlanner(routePlanner)
                    .build();
            response = client.execute(httpPost);
            if (response != null && response.getEntity() != null) {
                BufferedReader reader = null;
                reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
                StringBuilder result = new StringBuilder();
                String message = null;
                while ((message = reader.readLine()) != null) {
                    result.append(message).append(System.getProperty("line.separator"));
                }
                resultStr = result.toString();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (client != null) {
                try {
                    client.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return resultStr;
    }


    public static String sendJsonMessage(String reqUrl, HashMap<String, String> requestHeaderMap, String jsonStr) {
        CloseableHttpResponse response = null;
        CloseableHttpClient client = null;
        String resultStr = null;
        try {
            HttpPost httpPost = new HttpPost(reqUrl);
            StringEntity entityParams = new StringEntity(jsonStr, "utf-8");
            httpPost.setEntity(entityParams);
            httpPost.setHeader("Content-Type", "application/json");
            Iterator var12 = requestHeaderMap.entrySet().iterator();
            while (var12.hasNext()) {
                Map.Entry<String, String> header = (Map.Entry) var12.next();
                httpPost.setHeader((String) header.getKey(), (String) header.getValue());
            }
            client = HttpClients.createDefault();
            response = client.execute(httpPost);
            if (response != null && response.getEntity() != null) {
                BufferedReader reader = null;
                reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
                StringBuilder result = new StringBuilder();
                String message = null;
                while ((message = reader.readLine()) != null) {
                    result.append(message).append(System.getProperty("line.separator"));
                }
                resultStr = result.toString();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (client != null) {
                try {
                    client.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return resultStr;
    }


    /**
     * 向指定 URL 发送POST方法的请求
     *
     * @param url   发送请求的 URL
     * @param param 请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
     * @return 所代表远程资源的响应结果
     */
    public static String sendPostByProxy(String url, String param) {
        PrintWriter out = null;
        BufferedReader in = null;
        StringBuilder result = new StringBuilder();
        try {
            String urlNameString = url;
            log.info("sendPost - {}", urlNameString);
//            URL realUrl = new URL(urlNameString);
//            URLConnection conn = realUrl.openConnection();
            Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("117.45.139.84", 9006));
            HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection(proxy);

            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            conn.setRequestProperty("Accept-Charset", "utf-8");
            conn.setRequestProperty("contentType", "utf-8");
            conn.setDoOutput(true);
            conn.setDoInput(true);
            out = new PrintWriter(conn.getOutputStream());
            out.print(param);
            out.flush();
            in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
            String line;
            while ((line = in.readLine()) != null) {
                result.append(line);
            }
            log.info("recv - {}", result);
        } catch (ConnectException e) {
            log.error("调用HttpUtils.sendPost ConnectException, url=" + url + ",param=" + param, e);
        } catch (SocketTimeoutException e) {
            log.error("调用HttpUtils.sendPost SocketTimeoutException, url=" + url + ",param=" + param, e);
        } catch (IOException e) {
            log.error("调用HttpUtils.sendPost IOException, url=" + url + ",param=" + param, e);
        } catch (Exception e) {
            log.error("调用HttpsUtil.sendPost Exception, url=" + url + ",param=" + param, e);
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                log.error("调用in.close Exception, url=" + url + ",param=" + param, ex);
            }
        }
        return result.toString();
    }

    public static HttpResponse httpFormPost(String url, HashMap<String, String> requestHeaderMap, String cookies, HashMap<String, String> dataMap, String describe, String proxyIp) {
//        log.info("请求地址:{}", url);
        HttpResponse httpResponse = new HttpResponse();
        FormBody.Builder builder = new FormBody.Builder();
        Iterator var8 = dataMap.entrySet().iterator();
        StringBuffer stringBuffer = new StringBuffer("");
        while (var8.hasNext()) {
            Map.Entry<String, String> data = (Map.Entry) var8.next();
            builder.add((String) data.getKey(), (String) data.getValue());
            stringBuffer.append(data.getKey() + "=" + data.getValue() + "&");
        }

        FormBody formBody = builder.build();
//        log.info("请求参数：{}", new Object[]{stringBuffer.toString()});


        okhttp3.Request.Builder postBuilder = (new okhttp3.Request.Builder()).url(url).method("POST", formBody);
        Iterator var12 = requestHeaderMap.entrySet().iterator();

        while (var12.hasNext()) {
            Map.Entry<String, String> header = (Map.Entry) var12.next();
            postBuilder.addHeader((String) header.getKey(), (String) header.getValue());
        }

        Request request = postBuilder.build();
        Call call = getUnsafeOkHttpClient(proxyIp).newCall(request);

        try {
            Response response = call.execute();
            if (!response.isSuccessful()) {
                throw new IOException("Unexpected code " + response);
            } else {
                StringBuilder sb = new StringBuilder();
                Iterator var16 = response.headers("Set-Cookie").iterator();

                while (var16.hasNext()) {
                    String header = (String) var16.next();
                    if (!header.isEmpty()) {
                        sb.append(header.split(";")[0] + ";");
                    }
                }
                String body = response.body().string();
                Document document = Jsoup.parse(body);

                httpResponse.setDocument(document);
                if (sb.length() > 0) {
                    httpResponse.setCookie(sb.toString());
                    httpResponse.setCookieMap(getCookieMapByString(sb.toString()));
                }
                httpResponse.setIsSuccess(true);
                httpResponse.setBody(body);
                httpResponse.setIsSuccess(response.isSuccessful());
                httpResponse.setQuery(response.request().url().query());
                httpResponse.setHost(response.request().url().host());
//                log.info("请求：{}，内容:{}, 结果:{}", new Object[]{url, describe, response.isSuccessful()});
                return httpResponse;
            }
        } catch (IOException var18) {
            httpResponse.setIsSuccess(false);
            httpResponse.setMessage(var18.getMessage());
//            log.error("请求：{}，内容:{}, 结果:{}", new Object[]{url, describe, var18.getMessage()});
            return httpResponse;
        }
    }

    public static HttpResponse httpPost(String url, HashMap<String, String> requestHeaderMap, String cookies, HashMap<String, String> dataMap, String describe) {
        log.info("请求地址:{}", url);
        FormBody.Builder builder = new FormBody.Builder();
        Iterator var8 = dataMap.entrySet().iterator();
        StringBuffer stringBuffer = new StringBuffer("");
        while (var8.hasNext()) {
            Map.Entry<String, String> data = (Map.Entry) var8.next();
            builder.add((String) data.getKey(), (String) data.getValue());
            stringBuffer.append(data.getKey() + "=" + data.getValue() + "&");
        }

        FormBody formBody = builder.build();
        log.info("请求参数：{}", new Object[]{stringBuffer.toString()});

        OkHttpClient okHttpClient = OkHttpUtil.getInstance();
        OkHttpClient client = okHttpClient.newBuilder().proxy(getProxy(IP_URL)).build();
        okhttp3.Request.Builder postBuilder = (new okhttp3.Request.Builder()).url(url).addHeader("Cookie", cookies).post(formBody);
        Iterator var12 = requestHeaderMap.entrySet().iterator();

        while (var12.hasNext()) {
            Map.Entry<String, String> header = (Map.Entry) var12.next();
            postBuilder.addHeader((String) header.getKey(), (String) header.getValue());
        }

        Request request = postBuilder.build();
        Call call = client.newCall(request);
        HttpResponse httpResponse = new HttpResponse();
        try {
            Response response = call.execute();
            if (!response.isSuccessful()) {
                throw new IOException("Unexpected code " + response);
            } else {
                StringBuilder sb = new StringBuilder();
                Iterator var16 = response.headers("Set-Cookie").iterator();

                while (var16.hasNext()) {
                    String header = (String) var16.next();
                    if (!header.isEmpty()) {
                        sb.append(header.split(";")[0] + ";");
                    }
                }


                httpResponse.setBody(response.body().string());
                if (sb.length() > 0) {
                    httpResponse.setCookieMap(getCookieMapByString(sb.toString()));
                }
                httpResponse.setIsSuccess(true);
                httpResponse.setIsSuccess(response.isSuccessful());
                httpResponse.setQuery(response.request().url().query());
                httpResponse.setHost(response.request().url().host());
                response.close();
                log.info("请求：{}，内容:{}, 结果:{}", new Object[]{url, describe, response.isSuccessful()});
                return httpResponse;
            }
        } catch (IOException var18) {
            httpResponse.setIsSuccess(false);
            httpResponse.setMessage(var18.getMessage());
            log.error("请求：{}，内容:{}, 结果:{}", new Object[]{url, describe, var18.getMessage()});
            return httpResponse;
        }
    }


    public static HttpResponse httpFormGet(String url, HashMap<String, String> requestHeaderMap, String cookies, String describe) {
        //log.info("请求地址:{}", url);

        OkHttpClient okHttpClient = OkHttpUtil.getInstance();
        OkHttpClient client = okHttpClient.newBuilder().build();
        StringBuffer qrysb = new StringBuffer();
        for (Map.Entry<String, String> entry : requestHeaderMap.entrySet()) {
            qrysb.append(entry.getKey() + "=" + entry.getValue());
            qrysb.append("&");
        }
        String s = qrysb.toString();
        if (s.endsWith("&")) {
            s = StringUtils.substringBeforeLast(s, "&");
        }
        String qryUrl = url;
//        if(requestHeaderMap.size()!=0){
//            qryUrl = url +"?"+s;
//        }
        //log.info("参数:{}", qryUrl);
        okhttp3.Request.Builder builder = null;
        if (StringUtils.isNotBlank(cookies)) {
            builder = (new okhttp3.Request.Builder()).url(qryUrl).addHeader("cookie", cookies).get();
        } else {
            builder = (new okhttp3.Request.Builder()).url(qryUrl).get();
        }

        Iterator var12 = requestHeaderMap.entrySet().iterator();

        while (var12.hasNext()) {
            Map.Entry<String, String> header = (Map.Entry) var12.next();
            builder.addHeader((String) header.getKey(), (String) header.getValue());
        }


        Request request = builder.build();
        Call call = client.newCall(request);
        HttpResponse httpResponse = new HttpResponse();
        try {
            Response response = call.execute();
            if (!response.isSuccessful()) {
                throw new IOException("Unexpected code " + response);
            } else {

                httpResponse.setHost(response.request().url().host());
                httpResponse.setQuery(response.request().url().query());
                String body = response.body().string();
                httpResponse.setBody(body);
                httpResponse.setDocument(Jsoup.parse(body));
                //log.info("返回结果query:{}", response.request().url().toString());
                //log.info("host:{}", response.request().url().host());

                StringBuilder sb = new StringBuilder();
                Iterator var14 = response.headers("Set-Cookie").iterator();

                while (var14.hasNext()) {
                    String header = (String) var14.next();
                    if (!header.isEmpty()) {
                        sb.append(header.split(";")[0] + ";");
                    }
                }
                httpResponse.setIsSuccess(true);
                httpResponse.setLocation(response.header("Location"));
                httpResponse.setCookie(sb.toString());
                httpResponse.setCookieMap(getCookieMapByString(sb.toString()));
                httpResponse.setIsSuccess(response.isSuccessful());
                //log.info("请求：{}，内容:{}, 结果:{}", new Object[]{url, describe, body});
                return httpResponse;
            }
        } catch (IOException var16) {
            httpResponse.setIsSuccess(false);
            httpResponse.setMessage(var16.getMessage());
            //log.error("请求：{}，内容:{}, 结果:{}", new Object[]{url, describe, var16.getMessage()});
            return httpResponse;
        }
    }


    public static HttpResponse httpFormGet(String url, HashMap<String, String> requestHeaderMap, String cookies, String describe, String proxyIp) {
        //log.info("请求地址:{}", url);
//        OkHttpClient client = okHttpClient.newBuilder().build();

        StringBuffer qrysb = new StringBuffer();
        for (Map.Entry<String, String> entry : requestHeaderMap.entrySet()) {
            qrysb.append(entry.getKey() + "=" + entry.getValue());
            qrysb.append("&");
        }
        String s = qrysb.toString();
        if (s.endsWith("&")) {
            s = StringUtils.substringBeforeLast(s, "&");
        }
        String qryUrl = url;
//        if(requestHeaderMap.size()!=0){
//            qryUrl = url +"?"+s;
//        }
        //log.info("参数:{}", qryUrl);

        okhttp3.Request.Builder builder = (new okhttp3.Request.Builder()).url(qryUrl).addHeader("cookie", cookies).get();
        Iterator var12 = requestHeaderMap.entrySet().iterator();

        while (var12.hasNext()) {
            Map.Entry<String, String> header = (Map.Entry) var12.next();
            builder.addHeader((String) header.getKey(), (String) header.getValue());
        }


        Request request = builder.build();

        Call call = getUnsafeOkHttpClient(proxyIp).newCall(request);
        HttpResponse httpResponse = new HttpResponse();
        try {
            Response response = call.execute();
            if (!response.isSuccessful()) {
                throw new IOException("Unexpected code " + response);
            } else {

                httpResponse.setHost(response.request().url().host());
                httpResponse.setQuery(response.request().url().query());
                String body = response.body().string();
                httpResponse.setBody(body);
                httpResponse.setDocument(Jsoup.parse(body));
                //log.info("返回结果query:{}", response.request().url().toString());
                //log.info("host:{}", response.request().url().host());

                StringBuilder sb = new StringBuilder();
                Iterator var14 = response.headers("Set-Cookie").iterator();

                while (var14.hasNext()) {
                    String header = (String) var14.next();
                    if (!header.isEmpty()) {
                        sb.append(header.split(";")[0] + ";");
                    }
                }
                httpResponse.setCookie(sb.toString());
                httpResponse.setCookieMap(getCookieMapByString(sb.toString()));
                httpResponse.setIsSuccess(response.isSuccessful());
//                log.info("请求：{}，内容:{}, 结果:{}", new Object[]{url, describe, body});
                return httpResponse;
            }
        } catch (IOException var16) {
            httpResponse.setIsSuccess(false);
            httpResponse.setMessage(var16.getMessage());
//            log.error("请求：{}，内容:{}, 结果:{}", new Object[]{url, describe, var16.getMessage()});
            return httpResponse;
        }
    }

    public static HttpResponse httpGet(String url, HashMap<String, String> requestHeaderMap, String cookies, String describe) {
        log.info("请求地址:{}", url);

        OkHttpClient okHttpClient = OkHttpUtil.getInstance();
        OkHttpClient client = okHttpClient.newBuilder().build();

        okhttp3.Request.Builder builder = (new okhttp3.Request.Builder()).url(url).addHeader("cookie", cookies).get();
        Iterator var9 = requestHeaderMap.entrySet().iterator();

        while (var9.hasNext()) {
            Map.Entry<String, String> header = (Map.Entry) var9.next();
            builder.addHeader((String) header.getKey(), (String) header.getValue());
        }

        Request request = builder.build();
        Call call = client.newCall(request);

        try {
            Response response = call.execute();
            if (!response.isSuccessful()) {
                throw new IOException("Unexpected code " + response);
            } else {
                HttpResponse httpResponse = new HttpResponse();
                httpResponse.setHost(response.request().url().host());
                httpResponse.setQuery(response.request().url().query());
                httpResponse.setBody(response.body().string());
                log.info("返回结果query:{}", response.request().url().toString());
                log.info("host:{}", response.request().url().host());

                StringBuilder sb = new StringBuilder();
                Iterator var14 = response.headers("Set-Cookie").iterator();

                while (var14.hasNext()) {
                    String header = (String) var14.next();
                    if (!header.isEmpty()) {
                        sb.append(header.split(";")[0] + ";");
                    }
                }

                httpResponse.setCookieMap(getCookieMapByString(sb.toString()));
                httpResponse.setIsSuccess(response.isSuccessful());
                log.info("请求：{}，内容:{}, 结果:{}", new Object[]{url, describe, response.isSuccessful()});
                return httpResponse;
            }
        } catch (IOException var16) {
            log.error("请求：{}，内容:{}, 结果:{}", new Object[]{url, describe, var16.getMessage()});
            return null;
        }
    }

    public static HashMap<String, String> getCookieMapByString(String cookies) {
        HashMap<String, String> cookieMap = new HashMap();
        if (StringUtils.isBlank(cookies))
            return cookieMap;
        String[] list = cookies.split(";");
        String[] var4 = list;
        int var5 = list.length;

        for (int var6 = 0; var6 < var5; ++var6) {
            String cookie = var4[var6];
            String[] keyAndValue = cookie.split("=");
            if (keyAndValue.length >= 2)
                cookieMap.put(keyAndValue[0], cookie.substring(keyAndValue[0].length() + 1, cookie.length()));
            else
                cookieMap.put(keyAndValue[0], "");
        }

        return cookieMap;
    }

    private static Proxy getProxy(String proxy) {
        System.setProperty("jdk.http.auth.tunneling.disabledSchemes", "");
        System.setProperty("https.protocols", "TLSv1,TLSv1.1,TLSv1.2,SSLv3");
        if (proxy != null && !proxy.isEmpty()) {
            String[] proxyInfo = proxy.split(":");
            log.info("代理IP：{}，端口:{},", new Object[]{proxyInfo[0], Integer.parseInt(proxyInfo[1])});
            return new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyInfo[0], Integer.parseInt(proxyInfo[1])));
        } else {
            //log.error("企业代理IP：{}，端口:{},", new Object[]{this.proxyHost, this.proxyPort});

            //return new Proxy(Type.HTTP, new InetSocketAddress(this.proxyHost, this.proxyPort));
        }
        return null;
    }



    public static String getParam(String url, String name) {
        String params = url.substring(url.indexOf("?") + 1, url.length());
        Map<String, String> split = Splitter.on("&").withKeyValueSeparator("=").split(params);
        return split.get(name);
    }


    public static void main(String[] args) throws IOException {
//        String a ="__jdv=122270672|baidu|-|organic|not set|1630050814688; __jdu=16300508146871554389989; TrackID=1b5IuCVwnayp8jp_TIVl2vEPw_mkc6n9wN2yg5sYL548RAeLYOLOi_QH9xmYQN_HV2owbW6wnrFGyrB2Cs2T7ZTqQ8bn2_7-SbiOPMbnBmyU; pinId=_QJ7V77YNRG1ffsfn98I-w; pin=ldwallen; _tp=J%2BZ0CnTqktOLxbInQiBckQ%3D%3D; _pst=ldwallen; areaId=16; ipLoc-djd=16-1303-0-0; shshshfpa=f1cc544f-513b-f680-59be-13027015eb10-1630050916; mobilev=html5; mba_muid=16300508146871554389989; shshshfpb=gJ8E%20DBRe0VxMty0qJyN94Q%3D%3D; wxa_level=1; retina=1; webp=1; visitkey=64940260190972432; PPRD_P=UUID.16300508146871554389989; sc_width=400; jcap_dvzw_fp=_zeSZ4QHo2P0ZwVEXak_32KcoLzNhMdiuoiStJbpZlnfR_BdM8k9_0ZRywaCcKgwizanqQ==; whwswswws=; sbx_hot_h=null; wxmall_ptype=2; _mkjdcnsl=110; cartLastOpTime=1630172330; cartNum=1; kplTitleShow=1; wq_addr=1457520647%7C16_1303_48713_51478%7C%u798F%u5EFA_%u798F%u5DDE%u5E02_%u4ED3%u5C71%u533A_%u57CE%u533A%7C%u798F%u5EFA%u798F%u5DDE%u5E02%u4ED3%u5C71%u533A%u57CE%u533A%u4E0A%u4E09%u8DEF%u4E0E%u9996%u5C71%u8DEF%u4EA4%u6C47%u5904%u5411%u5357250%u7C73%u4E03%u8857%u5341%u4E8C%u5E9C11%u53F7%u697C%7C119.31347%2C26.03466; jdAddrId=16_1303_48713_51478; jdAddrName=%u798F%u5EFA_%u798F%u5DDE%u5E02_%u4ED3%u5C71%u533A_%u57CE%u533A; commonAddress=1457520647; regionAddress=16%2C1303%2C48713%2C51478; mitemAddrId=16_1303_48713_51478; mitemAddrName=%u798F%u5EFA%u798F%u5DDE%u5E02%u4ED3%u5C71%u533A%u57CE%u533A%u4E0A%u4E09%u8DEF%u4E0E%u9996%u5C71%u8DEF%u4EA4%u6C47%u5904%u5411%u5357250%u7C73%u4E03%u8857%u5341%u4E8C%u5E9C11%u53F7%u697C; _mkjdcn=ebb848e4ce9df4511a3e8361ca331109; cid=3; jxsid_s_u=https%3A//wqs.jd.com/my/accountv2.shtml; 3AB9D23F7A4B3C9B=6XC7KZLPBIXWMDHCMT2Y327KYWSJBUNFA6HZCI6GZB25FYFYT24S4YUQ4B4QRHALEF3KBV3NKMNILJOGWJI4NV3EFI; TrackerID=cNnbVsY_BKif4vy7lePmcAK1jhvT9GfAOQOStzoDagDS9y8mvpHUUywQbhdR7fI_SHhs-32rhw2IfrasBbSEmtJ6DD6wcYCn-u3jiiaTR2hBS6JachkCWnAW0YgUI8Sm; pt_key=AAJhK3PXADBl4DC3KZQzxLoBQFEupJnmenaknloL9W0HF9Ctrby18VdynW9rMvhJRxMVbSLnHYw; pt_pin=ldwallen; pt_token=5bvguvrp; pwdt_id=ldwallen; sfstoken=tk01mb9841bbfa8sMXgyeDJIa2tElWk8EfldLotYJJEtQKfBx8+BhvdfmN2/iQd75tfx2j15kaZ1q9/IlJEd2tj3Jq63; buy_uin=21863536654; jdpin=ldwallen; wq_skey=zm0E5CD4440AA3C6F3840BAEF1A5E24AF696C8222D10451A64F06FBD786B6C893FA2B2DDE2EE698B0B7216D2C71EA49012FE320C07E8DD5986C07748C65D01CF2BE696E5CBA19E8FA6D6C9C1C131053EC7; wq_uin=21863536654; __wga=1630237655306.1630237566808.1630172264678.1630051300292.6.4; jxsid_s_t=1630237655403; mcossmd=3f9ff0dc2813637446a9e74ef2b4e226; pinStatus=0; shshshfp=d8cdde37013bd69b467fa68bb0cc890a; __jdc=122270672; __jda=122270672.16300508146871554389989.1630050815.1630256972.1630261912.13; __jdb=122270672.3.16300508146871554389989|13.1630261912; mba_sid=16302619121315162611318865158.3; __jd_ref_cls=MCashierNew_ConfirmPayment";
//        HashMap<String,String> map = getCookieMapByString(a.replaceAll(" ",""));
//        System.out.println(map.get("3AB9D23F7A4B3C9B"));
//
//        String b ="https://pay.m.jd.com/cpay/newPay-index.html?appId=jd_m_shcost&payId=367726ed0dad4f3088bd55841fbaff8c";
//        System.out.println(getParam(b,"appId"));
//        String body = "sellerPercent=0&numOfInstallments=&canUseHuaBei=1&canUseDj=1&qrcode=3198A896609760CCC83471B2EB998A2B&app_id=2021001132638898&txnamt=2&paymentchannel=1&platform=2&auth_code=5258e150c7674f9182778f648ea6PX69&usrmp=13285985308&CUST_ID=60000002712860&remark=";
//        body ="CUST_ID=60000002712860&app_id=2021001132621388&auth_code=96999a8f6077458894549b574e06PX69&canUseDj=1&canUseHuaBei=1&paymentchannel=1&platform=2&qrcode=3198A896609760CCC83471B2EB998A2B&sellerPercent=2&txnamt=0.01&usrmp=13285985308";
//        map = new HashMap();
//        map.put("User-Agent","Nebula AlipayDefined(nt:WIFI,ws:360|0|3.0) AliApp(AP/10.0.18.062203) AlipayClient/10.0.18.062203 Language/zh-Hans useStatusBar/true");
//        map.put("cookie","HWWAFSESTIME=1652354364558;HWWAFSESID=c837c97f7e5f842576;A&3198A896609760CCC83471B2EB998A2B=2088002606948690");
//        String aa = sendPostRequest("https://yyfweb.postar.cn/postalpay/p/payAli",body,map);
//        System.out.println(aa);
//        String url ="https://www.douyin.com/webcast/wallet_api/diamond_buy_external_safe/?diamond_id=666666&source=10&way=0&aid=1128&short_id=102679264&fp=verify_l4zoxlhu_p9K40hpK_K1hZ_41kL_BYR9_nigKcGxn4ky0&customized_price=1000";
//        String cookie = "MONITOR_WEB_ID=8e511bc1-2dcb-9935-a832-88e3b4c1b85c;passport_csrf_token=64cdcdfb803d3e5c777f26ad397962d1;passport_csrf_token_default=64cdcdfb803d3e5c777f26ad397962d1;BIDUPSID=EBA78010F73DB0D53E14246F0A0A3BB3;_tea_utm_cache_10006=undefined;MONITOR_WEB_ID=7a09a309-7470-430d-9815-8041286a8f79;MONITOR_DEVICE_ID=0c3e117e-2c27-41fa-a6ea-6379dbe70214;MONITOR_WEB_ID=c060fd74-1925-48d7-9d85-8e4947c5bc5a;ttwid=1%7CuMQ3k9CcVe_NOiDmqwzWJaEtEQ2iDfkGHELnTeYmK8Q%7C1656490057%7C8c54b4e9c5c103c4a4ba7476b0dc8ddfe110a96b76f5cf21bda8bf26b3500a1a;s_v_web_id=verify_l4zbesxn_V7GJsZI7_5mUI_4WQP_99JY_jEUiNiZ2sHDn;odin_tt=ab4e59838643829ecde060875c3c02be255be0103bffda67f7d245426a55c9d85da8aca43855a46fcb4b41b1ba0190165e7ac9da26b21959d6499aed1b1ce073;n_mh=WQehLoIGFgIx4f2T4TruFV39yXU8B8x_WwbswOYP8WE;sso_uid_tt=40a9438e048ac16db6f9ffbd3c35f9e9;sso_uid_tt_ss=40a9438e048ac16db6f9ffbd3c35f9e9;toutiao_sso_user=f981d6c87a9561e3e70ce88c790766d0;toutiao_sso_user_ss=f981d6c87a9561e3e70ce88c790766d0;sid_ucp_sso_v1=1.0.0-KGQ2MTE4OTk4Y2YyY2E2MjViYWU4Mzg4MzBjNzE1MWZmY2VmMWI5MjEKHQiwqYvKjwIQ4ZDwlQYYlk4gDDDplqzPBTgGQPQHGgJsZiIgZjk4MWQ2Yzg3YTk1NjFlM2U3MGNlODhjNzkwNzY2ZDA;ssid_ucp_sso_v1=1.0.0-KGQ2MTE4OTk4Y2YyY2E2MjViYWU4Mzg4MzBjNzE1MWZmY2VmMWI5MjEKHQiwqYvKjwIQ4ZDwlQYYlk4gDDDplqzPBTgGQPQHGgJsZiIgZjk4MWQ2Yzg3YTk1NjFlM2U3MGNlODhjNzkwNzY2ZDA;passport_csrf_token=fb4b4e387e36ff9400acf540c856016e;passport_csrf_token_default=fb4b4e387e36ff9400acf540c856016e;passport_auth_status=691fa9110c5a68f10a579b0cf12effb1%2C;passport_auth_status_ss=691fa9110c5a68f10a579b0cf12effb1%2C;sid_guard=28d2e32cda8d16ebaeeb65d38cbe4e7f%7C1656490083%7C5183998%7CSun%2C+28-Aug-2022+08%3A08%3A01+GMT;uid_tt=742d8403508ae03a8963d392e0ca9510;uid_tt_ss=742d8403508ae03a8963d392e0ca9510;sid_tt=28d2e32cda8d16ebaeeb65d38cbe4e7f;sessionid=28d2e32cda8d16ebaeeb65d38cbe4e7f;sessionid_ss=28d2e32cda8d16ebaeeb65d38cbe4e7f;sid_ucp_v1=1.0.0-KDI4ODBkNmY0NDVlMjhlODg1ZGE0OWI3YmY2OTNlZTkzOTM0MGQyZDcKFQiwqYvKjwIQ45DwlQYYlk44BkD0BxoCbGYiIDI4ZDJlMzJjZGE4ZDE2ZWJhZWViNjVkMzhjYmU0ZTdm;ssid_ucp_v1=1.0.0-KDI4ODBkNmY0NDVlMjhlODg1ZGE0OWI3YmY2OTNlZTkzOTM0MGQyZDcKFQiwqYvKjwIQ45DwlQYYlk44BkD0BxoCbGYiIDI4ZDJlMzJjZGE4ZDE2ZWJhZWViNjVkMzhjYmU0ZTdm;MONITOR_WEB_ID=c060fd74-1925-48d7-9d85-8e4947c5bc5a;MONITOR_WEB_ID=c060fd74-1925-48d7-9d85-8e4947c5bc5a;ttwid=1%7CuMQ3k9CcVe_NOiDmqwzWJaEtEQ2iDfkGHELnTeYmK8Q%7C1656490057%7C8c54b4e9c5c103c4a4ba7476b0dc8ddfe110a96b76f5cf21bda8bf26b3500a1a;s_v_web_id=verify_l4zbfddy_A5uCYI4f_jNPN_4Tyr_9hsC_UNOSs5b1gkyk;ttwid=1%7CuMQ3k9CcVe_NOiDmqwzWJaEtEQ2iDfkGHELnTeYmK8Q%7C1656490057%7C8c54b4e9c5c103c4a4ba7476b0dc8ddfe110a96b76f5cf21bda8bf26b3500a1a;msToken=VXHqAM_UVWj2wEUxykP_RtVwco7TB0C9y9bMWmoj_1J6yiWfXqE6RIuSjximOJAZ4GzowJhPYxHrsFWVOu6Jgb4CEoLdvKLAeK89gGA8rI42oMBN6uaNFNo2DLiE0w==;msToken=VXHqAM_UVWj2wEUxykP_RtVwco7TB0C9y9bMWmoj_1J6yiWfXqE6RIuSjximOJAZ4GzowJhPYxHrsFWVOu6Jgb4CEoLdvKLAeK89gGA8rI42oMBN6uaNFNo2DLiE0w==;";
//        cn.hutool.http.HttpResponse aaa = HttpUtil.createGet(url).header("cookie",cookie).execute();
//        System.out.println(aaa.body());
//
//        org.apache.http.client.fluent.Request request = org.apache.http.client.fluent.Request.Post("https://www.douyin.com/webcast/wallet_api/diamond_buy_external_safe/?diamond_id=888888&source=10&way=0&aid=1128&short_id=xiannv1028.&open_id=&fp=verify_l4zqyyjg_6tIlzmht_PIwS_4zvo_9qGz_jVvn7QA1zxZI&platform=iphone&customized_price=5000&extra=%7B%22domin_type%22:1,%22uuid%22:%227114682825769682439%22,%22sharkParams%22:%22%7B%5C%22screen_size%5C%22:%7B%5C%22x%5C%22:390,%5C%22y%5C%22:844%7D,%5C%22mouse_area%5C%22:%7B%5C%22x%5C%22:250,%5C%22y%5C%22:611%7D,%5C%22page_stay_time%5C%22:39%7D%22%7D&guide_source=douyin_mobile&msToken=vyPtynwpU1AhfsY80Dwryo3HkgnPEz12XwW8DnTvXFrES2vd_dRgJLEHiXA7G1hmXL1CrtgPdwyicd0b3_VtgUi39gZcJ8wk7htbzL3vfebTOlkV69Q8&X-Bogus=DFSzswVLRAvANJ0oSf7yZmuyRsOh&_signature=_02B4Z6wo000013kWcxAAAIDDo7RTiMtDpGN5FneAAL0FloGuZmQG7B3meYEjjz5EsqwrowLNNAPGxFXjmEkSae98A.m7NZm0fv46ZNGrIoPYc-xWWQ9qM67aI4tQRfk.kSY3Zw8FIShZBt5pa4");
//        org.apache.http.HttpResponse httpResponse = request.execute().returnResponse();
////        System.out.println(httpResponse.getStatusLine());
//        request.setHeader("User-Agent", "Apipost client Runtime/+https://www.apipost.cn/");
//        request.setHeader("Cookie", "sessionid_ss=9559d67be3b26be140e3638f9e96b717");
//        request.setHeader("Content-Type", "application/x-www-form-urlencoded");
//        httpResponse = request.execute().returnResponse();
//        System.out.println(httpResponse.getStatusLine());
//        if (httpResponse.getEntity() != null) {
//            String html = EntityUtils.toString(httpResponse.getEntity());
//            System.out.println(html);
//        }
        String url = "https://e.o2obest.cn/api/headICRecharge/recharge?ajax=1&cezToken=c10960c6630d23dd62f498d9e62cc5c0&companyKey=874d8c821358a5e26f2524b10f43a292&token=A5CDqWtMMgpXws55fk6vTMuJENb3GAZ8NyiuHqKP8cYI1RnvEXt0XyIZfyan43svkB2u+xfg0UaDel2y2gFFqdsIP+0aLk0euzZRmeINbiXaDLbljCQJmjDT4F5y1mcw6n6ZVa0FA+7EyzB6p74kze3uaxRDg9qtIWwvbedYhpw=@lVQPZaG/r0AG4co9Mg+2iuETvENSwWD8S32ChSpnVOAM82Tvm02W4JhF0Uqao2t21jF/mCDB9e/NZBs0jdY32laWq+2Rf3l5QpKK6ZdAR0Q2nnqWnmzWY/UoTGoiEX3R/W9mnveWGtXFP85YUTpZk43aTVZCRyfxxETrkmiD61ONFAFw95rB7aev0wcJHGbdGtY5rlJT4wrt5FIYw/VoQC5yg2bPicR9uYJI/dNgs5BTCoIcW9Vo9A==&version=3.4.0";
//        HttpResponse httpResponse = getKmtPayToken("https://test-pay.52pay.com/api/qrcode/alipayRedirectUrl/eyJtY2hJZCI6IjIxMDAyODExIiwicGF5QW1vdW50IjoiIiwic3RvcmVJZCI6IjEwNTMxIiwib3BlcmF0b3JJZCI6Ijk5MzUiLCJwcmVRcmNvZGVJZCI6IjIyNjcifQ==",new HashMap<>(),"","");
//        System.out.println(httpResponse);
//        String a = HttpUtil.get(url);
//
//        System.out.println("hutool:" + a);

//        HttpResponse a = httpFormGet(url,new HashMap<>(),cookie,"","106.116.215.52:4341");
//        System.out.println(a.getBody());
        HashMap<String, String> headerMap = new HashMap();
        headerMap.put("User-Agent","Mozilla/5.0 (iPhone; CPU iPhone OS 17_1_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/21B101 Ariver/1.1.0 AliApp(AP/10.5.55.6000) Nebula WK RVKType(1) AlipayDefined(nt:WIFI,ws:390|780|3.0) AlipayClient/10.5.55.6000 Alipay Language/zh-Hans Region/CN NebulaX/1.0.0");
        HashMap<String, String> dataMap = new HashMap();
        HttpResponse httpResponse = HttpUtils.httpFormGet("http://bapi.51daili.com/getapi2?linePoolIndex=-1&packid=2&time=5&qty=1&port=1&format=json&ct=1&regionCode=321100&usertype=17&uid=51099&accessName=zjdadnim&accessPassword=967330F429E9D286617E7DE128684D46&skey=autoaddwhiteip", new HashMap<>(), "", "SYB获取IP代理");

        //{"code":0,"data":[{"ip":"27.155.222.47","port":"4331"}],"msg":"0","success":true}
        JSONObject proxyObj = JSONObject.parseObject(httpResponse.getBody());

        JSONArray proxyData = proxyObj.getJSONArray("data");
        JSONObject proData = proxyData.getJSONObject(0);
        String ip = proData.getString("ip");
        String prot = proData.getString("port");
//        httpFormGet("https://test-pay.52pay.com/api/qrcode/toQRCodePage?mchId=21002811&storeId=10531&operatorId=&payAmount=0&qrId=1865",headerMap,"","","125.77.33.25:4338");
        httpResponse =  httpFormGet("https://payapp.wechatpay.cn/receiptwxmgr/receipt/create?miniprogram_version=3.15.10&fee=30000&remark=&remark_pic_urls=&option_list=%5B%5D&receipt_item_list=%5B%5D&account_id=oMdKm5KMy6CkQKQPBYMrPgXbqQy0&account_type=2&sid=BAG04zWvDtQm8lrEF51eDXikXyWfJDL2FWxH_uGdiO7grg",headerMap,"","",ip+":"+prot);
        System.out.println(JSONObject.toJSONString(httpResponse));
        httpResponse =  httpFormGet("https://www.baidu.com",headerMap,"","",ip+":"+prot);
        System.out.println(JSONObject.toJSONString(httpResponse));
    }


    /**
     * 输入一个url,
     * 返回这个url对应的html代码
     *
     * @param urlStr:网址
     * @param paramsMap 提交参数;键=值
     * @return 返回网址对应的html代码
     */
    public static String methodPost(String urlStr, Map<String, String> paramsMap) {
        //ConstatFinalUtil.SYS_LOGGER.info("--methodGet--url:{}",urlStr);
        StringBuffer sb = new StringBuffer();
        try {
            URL url = new URL(urlStr);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();

            /* Post请求,必须加以下操作 */
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setRequestMethod("POST");

            /* 获取网址对应的输入流和输出流 */
            OutputStream os = connection.getOutputStream();
            BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));

            /* 先向服务器写数据
             * 如何将我们的参数写到输出流呢???
             * 得遵循HTTP协议,看浏览器怎么做,我们也怎么做
             *
             * URL get中的字符串
             * method=submit&email=aaa&password=bbbb
             *  */
            StringBuffer paramSb = new StringBuffer();
            for (Iterator iterator = paramsMap.entrySet().iterator(); iterator.hasNext(); ) {
                Map.Entry me = (Map.Entry) iterator.next();
                String key = me.getKey() + "";
                String value = me.getValue() + "";
                paramSb.append(key + "=" + value + "&");
            }
            /*
             * method=submit&email=aaa&password=bbbb
             * email=bb&method=submit&password=cc
             * */
            bw.write(paramSb.toString());
            bw.flush();
            bw.close();

            InputStream is = connection.getInputStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8"));

            String line = "";
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }

            br.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return sb.toString();
    }


    public static void buildPayParams(StringBuilder sb, Map<String, String> payParams) {
        List<String> keys = new ArrayList<String>(payParams.keySet());
        Collections.sort(keys);
        for (String key : keys) {
//            log.info(key+"  值："+payParams.get(key));
            if (payParams.get(key) == null || String.valueOf(payParams.get(key)).equals("")) {
                continue;
            }
            sb.append(key).append("=");
            sb.append(String.valueOf(payParams.get(key)));
            sb.append("&");
        }
        sb.setLength(sb.length() - 1);
    }

    public static String sendPostRequest(String url, String param) {

        String responseContent = "";
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse response = null;
        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectTimeout(10000).setConnectionRequestTimeout(10000)
                .setSocketTimeout(10000).build();
        try {

            HttpPost httpPost = new HttpPost(url);
            httpPost.setConfig(requestConfig);
            StringEntity entity = new StringEntity(param, "utf-8");// 解决中文乱码问题
            httpPost.setEntity(entity);
            httpPost.addHeader(HTTP.CONTENT_TYPE, "application/x-www-form-urlencoded");
            if (url.contains("https://")) {
                SSLConnectionSocketFactory scsf = new SSLConnectionSocketFactory(SSLContexts.custom().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build(), NoopHostnameVerifier.INSTANCE);
                httpClient = HttpClients.custom().setSSLSocketFactory(scsf).build();
            } else {
                httpClient = HttpClients.createDefault();
            }
            response = httpClient.execute(httpPost);
            System.out.println(response.getStatusLine().getStatusCode() + "\n");
            HttpEntity result = response.getEntity();
            responseContent = EntityUtils.toString(result, "UTF-8");
            System.out.println(responseContent);
        } catch (Exception e) {
            System.out.println("发送 POST 请求出现异常！" + e);
            e.printStackTrace();
        }
        // 使用finally块来关闭输出流、输入流
        finally {
            try {
                if (httpClient != null) {
                    httpClient.close();
                }
                if (response != null) {
                    response.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        return responseContent;
    }


    public static String douyinGet(String urlStr, String cookie) throws IOException {
//        org.apache.http.client.fluent.Request request = org.apache.http.client.fluent.Request.Get(urlStr);
//        RequestConfig defaultConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD).build();
//        request.setConfig(defaultConfig);
//        request.setHeader("Cookie", cookie);
//        org.apache.http.HttpResponse httpResponse = request.execute().returnResponse();
//        String html = "";
//        if (httpResponse.getEntity() != null) {
//            html = EntityUtils.toString(httpResponse.getEntity());
//        }
        return "html";
    }




    public static HttpResponse getKmtPayToken(String url, HashMap<String, String> requestHeaderMap, String cookies, String describe,String proxyIp) {
        //log.info("请求地址:{}", url);

        OkHttpClient okHttpClient = OkHttpUtil.getInstance();
        OkHttpClient client = null;
        if (StringUtils.isNotBlank(proxyIp)) {
            log.info("代理IP:{}", proxyIp);
            client = okHttpClient.newBuilder().proxy(getProxy(proxyIp)).build();
        } else {
            client = okHttpClient.newBuilder().build();
        }
        StringBuffer qrysb = new StringBuffer();
        for (Map.Entry<String, String> entry : requestHeaderMap.entrySet()) {
            qrysb.append(entry.getKey() + "=" + entry.getValue());
            qrysb.append("&");
        }
        String s = qrysb.toString();
        if (s.endsWith("&")) {
            s = StringUtils.substringBeforeLast(s, "&");
        }
        String qryUrl = url;
//        if(requestHeaderMap.size()!=0){
//            qryUrl = url +"?"+s;
//        }
        //log.info("参数:{}", qryUrl);

        okhttp3.Request.Builder builder = null;
        if (StringUtils.isNotBlank(cookies)) {
            builder = (new okhttp3.Request.Builder()).url(qryUrl).addHeader("cookie", cookies).get();
        } else {
            builder = (new okhttp3.Request.Builder()).url(qryUrl).get();
        }

        Iterator var12 = requestHeaderMap.entrySet().iterator();

        while (var12.hasNext()) {
            Map.Entry<String, String> header = (Map.Entry) var12.next();
            builder.addHeader((String) header.getKey(), (String) header.getValue());
        }


        Request request = builder.build();
        Call call = client.newCall(request);

        try {
            Response response = call.execute();
            if (!response.isSuccessful()) {
                throw new IOException("Unexpected code " + response);
            } else {
                String uuu = response.request().url().url().toString();
                HttpResponse httpResponse = new HttpResponse();
                httpResponse.setHost(response.request().url().host());
                httpResponse.setQuery(response.request().url().query());
                String body = response.body().string();
                httpResponse.setBody(body);
                httpResponse.setDocument(Jsoup.parse(body));
                //log.info("返回结果query:{}", response.request().url().toString());
                //log.info("host:{}", response.request().url().host());

                StringBuilder sb = new StringBuilder();
                Iterator var14 = response.headers("Set-Cookie").iterator();

                while (var14.hasNext()) {
                    String header = (String) var14.next();
                    if (!header.isEmpty()) {
                        sb.append(header.split(";")[0] + ";");
                    }
                }
                httpResponse.setLocation(uuu);
                httpResponse.setCookie(sb.toString());
                httpResponse.setCookieMap(getCookieMapByString(sb.toString()));
                httpResponse.setIsSuccess(response.isSuccessful());
                //log.info("请求：{}，内容:{}, 结果:{}", new Object[]{url, describe, body});
                return httpResponse;
            }
        } catch (IOException var16) {
            //log.error("请求：{}，内容:{}, 结果:{}", new Object[]{url, describe, var16.getMessage()});
            return null;
        }
    }

    public static String submit(String submitUrl, Map<String, String> params) throws Exception
    {
        String response = "";
        if (null == submitUrl || "".equals(submitUrl))
            throw new IllegalArgumentException("提交地址参数无效！");
        if (null == params)
            throw new IllegalArgumentException("报文参数无效！");
        method.setURI(new URI(submitUrl));
        httpTransport.setMethod(method);
        if (submitUrl.startsWith("https"))
        {
            response = httpTransport.submit_https(params);
        }
        else
        {
            response = httpTransport.submit(params);
        }
        return response;
    }

    public static OkHttpClient getUnsafeOkHttpClient(String proxyIp) {
        try {
            // 创建一个信任所有证书的TrustManager
            final TrustManager[] trustAllCerts = new TrustManager[]{
                    new X509TrustManager() {
                        @Override
                        public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                        }

                        @Override
                        public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                        }

                        @Override
                        public X509Certificate[] getAcceptedIssuers() {
                            return new X509Certificate[0];
                        }
                    }
            };

            // 创建一个不验证证书的 SSLContext，并使用上面的TrustManager初始化
            SSLContext sslContext = SSLContext.getInstance("SSL");
            sslContext.init(null, trustAllCerts, new java.security.SecureRandom());

            // 使用上面创建的SSLContext创建一个SSLSocketFactory
            javax.net.ssl.SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();

            OkHttpClient.Builder builder = new OkHttpClient.Builder();
            if(StringUtils.isNotBlank(proxyIp)){
                builder.proxy(getProxy(proxyIp));
            }
            builder.sslSocketFactory(sslSocketFactory, (X509TrustManager) trustAllCerts[0]);
            builder.hostnameVerifier((hostname, session) -> true);
            builder.readTimeout(2, TimeUnit.MINUTES);
            builder.connectTimeout(2, TimeUnit.MINUTES);
            builder.retryOnConnectionFailure(true);
            return builder.build();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static String getParamByUrl(String url, String name) {

        String query = StrUtil.subAfter(url, "?", false);

        // 使用Hutool的MapUtil来转换参数为Map
        Map<String, String> paramMap = HttpUtil.decodeParamMap(query,"UTF-8");

        // 获取特定的参数
        String param1 = paramMap.get(name);

        // 打印结果
        System.out.println("param1: " + param1);
        return  param1;
    }
}
